package com.terra;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.lamerman.FileDialog;

public class MakeCompassView extends Activity implements OnClickListener {
	
	TextView textTCPage;
	EditText textDistance;
	EditText textBearing;
	RadioButton optionWalking;
	RadioButton optionDriving;
	String strMode = "d";
	TextView GPSText;
	TextView TargetText;
	TextView GPSStatus;

	Rose rose;

	MyTimer updateTimer;
	String strTCID="";
	
	Bundle b;
	public static final int REQUEST_SAVE = 1;
	public static final int REQUEST_LOAD = 2;
	
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		//Log.v("Debug", "Creating compass view");
		b = getIntent().getExtras();

		strTCID = b.getString("TCID");
		
		Globals.dTargetLat = b.getInt("LAT")/1e6;
		Globals.dTargetLon = b.getInt("LON")/1e6;
			
		setContentView(R.layout.compass);
		
		GPSText = (TextView) findViewById(R.id.textViewGPS);
		GPSStatus = (TextView) findViewById(R.id.textViewTracking);
		TargetText = (TextView) findViewById(R.id.textViewTarget);
		
		GPSText.setText("---");
		GPSStatus.setText("---");
		TargetText.setText("---");
		
		rose = (Rose)findViewById(R.id.imageCompassRose);

		Button webButton = (Button) findViewById(R.id.buttonWebPage);
		webButton.setOnClickListener(this);
		
		Button webLocalButton = (Button) findViewById(R.id.buttonLocalWebPage);
		webLocalButton.setOnClickListener(this);
		
		Button navButton = (Button) findViewById(R.id.buttonNavTo);
		navButton.setOnClickListener(this);
		
		optionWalking = (RadioButton) findViewById(R.id.optionWalking);
		optionWalking.setOnClickListener(this);
		
		optionDriving = (RadioButton) findViewById(R.id.optionDriving);
		optionDriving.setOnClickListener(this);
		optionDriving.setChecked(true);

		textTCPage = (TextView) findViewById(R.id.textTCPage);
		textTCPage.setText(b.getString("TCNAME"));
		
		textDistance = (EditText) findViewById(R.id.editDistance);
		textDistance.setText("Distance");
		textBearing = (EditText) findViewById(R.id.editBearing);
		textBearing.setText("Bearing");
		DistanceBearing();
		updateTimer = new MyTimer(15000, 1000);
		updateTimer.compass = this;
		updateTimer.bRunning = true;
		updateTimer.start();
	}
	
    protected void onPause() {
    	updateTimer.bRunning = false;
        super.onPause();
    }	
    
    protected void onResume() {
    	updateTimer.bRunning = true;
    	updateTimer.start();
        super.onPause();

    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.detailsmenu, menu);
        return true;
    }
    
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
			
		case R.id.addwaypoint:
			WaypointDialog wpDialog = new WaypointDialog(this, strTCID);
			wpDialog.show();
			break;
			
		case R.id.savewaypoints:
    		Intent fileIntent = new Intent(this, FileDialog.class);
			fileIntent.putExtra(FileDialog.START_PATH, "/sdcard");
			fileIntent.putExtra(FileDialog.LOADSAVE, "SAVE");
    		startActivityForResult(fileIntent, REQUEST_SAVE);
			break;
			
		case R.id.loadwaypoints:
    		Intent fileIntent2 = new Intent(this, FileDialog.class);
			fileIntent2.putExtra(FileDialog.START_PATH, "/sdcard");
			fileIntent2.putExtra(FileDialog.LOADSAVE, "LOAD");
    		startActivityForResult(fileIntent2, REQUEST_LOAD);
			break;

		case R.id.clearwaypoints:
        	Toast toast = Toast.makeText(this, "Clearing user wpts", Toast.LENGTH_SHORT);
        	toast.show();
        	
        	Globals.mapView.getOverlays().clear();
        	Globals.mapView.getOverlays().add(Globals.TCOverlay);
        	Globals.mapView.getOverlays().add(Globals.myLocationOverlay);
        	Globals.TempOverlay = null; 
			break;
			

		}
		return true;
	}
	
    public synchronized void onActivityResult(final int requestCode,
            int resultCode, final Intent data) {
    		String filePath;
    	
            if (resultCode == Activity.RESULT_OK) {
            		
            		filePath = data.getStringExtra(FileDialog.RESULT_PATH);
                    if (requestCode == REQUEST_SAVE) {
                             Log.d("Debug", "Saving wpts..."+filePath);
                             if( Globals.TempOverlay!=null )
                            	 Globals.WriteGPX(filePath);
                             
                    } else if (requestCode == REQUEST_LOAD) {
                    	Log.d("Debug", "Loading wpts..."+filePath);

                    	Globals.TempOverlay = new MapItemizedOverlay(Globals.drawableRedPin, this, Globals.mapView);
                    	MyCacheHandler myCaches = new MyCacheHandler();
                    	myCaches.LoadCaches(filePath, Globals.TempOverlay);
                    	Log.d("Debug", "Overlay size -> "+Globals.TempOverlay.size());
                    	Globals.mapView.getOverlays().clear();
                    	Globals.mapView.getOverlays().add(Globals.TCOverlay);
                    	Globals.mapView.getOverlays().add(Globals.TempOverlay);
                    	Globals.mapView.getOverlays().add(Globals.myLocationOverlay);
                    	
                    }   
            } else if (resultCode == Activity.RESULT_CANCELED) {
            	Log.d("Debug", "wpt Request cancelled");
            }
    }
    
    public void onClick(View v) {
    	
    	switch(v.getId() ) {
    	
    		case R.id.buttonLocalWebPage:
				//Uri uriLocal = Uri.fromFile(Globals.strLocalHTMLPath+"/"+b.getString("TCID")+".html");
    			//Log.d("Debug", "URL->{"+Globals.strLocalHTMLPath+"/"+b.getString("TCID")+".html}");
    			
        		Intent htmlIntent = new Intent(this, WebViewer.class);
        		htmlIntent.putExtras(b);
        		startActivity(htmlIntent);
			break;
    		
	    	case R.id.buttonWebPage:
	    		//Log.d("Debug", "Go to ("+b.getString("TCID")+") <"+b.getString("LINK")+">");
				Intent intent = new Intent(Intent.ACTION_VIEW);
				Uri uri = Uri.parse(b.getString("LINK"));
				intent.setData(uri);
				startActivity(intent);
			break;
		
	    	case R.id.buttonNavTo:
	    		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:ll=" + Globals.dTargetLat + "," + Globals.dTargetLon + "&mode="+strMode+"")));
	    		break;
	    		
	    	case R.id.optionWalking:
	    		strMode = "w";
	    		break;
	    		
	    	case R.id.optionDriving:
	    		strMode = "d";
	    		break;
	    		
    	}
    }
    
    public void DistanceBearing() {//double lat1, double lon1, double lat2, double lon2) {
    	
    	double lat1 = Globals.dGPSLat;
    	double lon1 = Globals.dGPSLon;
    	double lat2 = Globals.dTargetLat;
    	double lon2 = Globals.dTargetLon;
    	
    	double R = 6371; // km
    	double dLat = Math.toRadians(lat2-lat1);
    	double dLon = Math.toRadians(lon2-lon1);
    	lat1 = Math.toRadians(lat1);
    	lat2 = Math.toRadians(lat2);

    	double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    	        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    	double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    	double d = R * c;
    	
    	double y = Math.sin(dLon) * Math.cos(lat2);
    	double x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
    	float brng = (float) Math.toDegrees(Math.atan2(y, x));
    	   	
    	// 0.17 km ~ 557 ft
    	// disp in miles further than that, ft less than that
    	String strDistanceUnits = " Miles";
    	if( Globals.strUnits.equalsIgnoreCase("English") ) {
	    	if( d > 0.17 )
	    		d *= 0.621371192;  //km to miles
	    	else {
	    		d *= 0.621371192 * 5280; //km to feet
	    		strDistanceUnits = " Ft";
	    	}
    	}
    	else {
	    	if( d > 0.17 ) {
	    		d *= 1;  // leave in km
	    		strDistanceUnits = " km";
	    	}
	    	else {
	    		d *= 0.001; // change to meters
	    		strDistanceUnits = " M";
	    	}
    	}
    	
    	NumberFormat formatter = new DecimalFormat("0.00");
    	String strDistance = formatter.format(d) + strDistanceUnits;  // -001235
    	String strBearing = formatter.format(brng);  // -001235
    	textDistance.setText(strDistance);
    	textBearing.setText(strBearing);
    	rose.SetBearing(brng);
    	rose.update();
    	
		String strGPS = "GPS " + Globals.dGPSLat + ", " + Globals.dGPSLon;
		String strStat = "Stat Loc " + Globals.myLocationOverlay.isMyLocationEnabled() + " Compass " + Globals.myLocationOverlay.isCompassEnabled() + " Trk " + Globals.bTrackGPS;
		String strTarg = "Target " + Globals.dTargetLat + ", " + Globals.dTargetLon;
		
		GPSText.setText(strGPS);
		GPSStatus.setText(strStat);
		TargetText.setText(strTarg);
    }
    

}
